/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.pbs.status;

import java.io.IOException;
import java.net.Socket;
import java.util.Collection;
import java.util.Date;
import java.util.LinkedList;

import jp.aist.gtrc.plus.scheduler.node.NodeInfo;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.PBSBatchClient;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.reply.*;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.request.*;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.request.BatchRequestHoldJob.HoldJobType;
import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSErrorCode;
import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSException;
import jp.aist.gtrc.plus.scheduler.status.JobID;
import jp.aist.gtrc.plus.scheduler.status.JobStatus;
import jp.aist.gtrc.plus.scheduler.status.MainServer;
import jp.aist.gtrc.plus.scheduler.status.NodeStatus;
import jp.aist.gtrc.plus.scheduler.status.QueueStatus;
import jp.aist.gtrc.plus.scheduler.status.ServerStatus;
import jp.aist.gtrc.plus.scheduler.sys.SchedulerException;
import jp.aist.gtrc.plus.scheduler.sys.SignalType;


public class PBSMainServer extends PBSBatchClient implements MainServer {

	public static final int PROTOCOL_TYPE = 2;
	public static final int PROTOCOL_VERSION = 1;

	static {
		BatchRequest.setDefaultRequester(System.getProperty("user.name"));
	}

	public PBSMainServer(Socket sock) {

		super();
		setSocket(sock);

	}

	public boolean isConnected() {

		Socket s = getSocket();
		return ((s != null) && (s.isConnected()));

	}

	public void disconnect() {

		Socket sock = getSocket();
		if (sock != null) {
			BatchRequestDisconnect request = new BatchRequestDisconnect();
			try {
				serverCall(request);
			} catch (PBSException e) {
				// no-Reply, ignore exception
			}

			try {
				sock.close();
			} catch (IOException e) {
				// ignore exception
			}

			setSocket(null);
		}
	}

	public ServerStatus getServerStatus() throws SchedulerException {

		BatchRequestStatusServer request = new BatchRequestStatusServer();
		BatchReplyStatusServer reply = (BatchReplyStatusServer)serverCall(request);

		return reply.getStatus();

	}

	public Collection<NodeStatus> getNodeStatus() throws SchedulerException {

		BatchRequestStatusNode request = new BatchRequestStatusNode();
		BatchReplyStatusNode reply = (BatchReplyStatusNode)serverCall(request);

		return reply.getAllStatus();

	}

	public Collection<QueueStatus> getQueueStatus() throws SchedulerException {

		BatchRequestStatusQueue request = new BatchRequestStatusQueue();
		BatchReplyStatusQueue reply = (BatchReplyStatusQueue)serverCall(request);

		return reply.getAllStatus();

	}

	public Collection<JobStatus> getJobStatus() throws SchedulerException {
		// TODO! performance
		LinkedList<JobStatus> jobList = new LinkedList<JobStatus>();
		for (QueueStatus q : getQueueStatus()) {
			for (JobStatus j : getJobStatus(q)) {
				jobList.add(j);
			}
		}
                System.out.println("PBSMainServer gots " + jobList.size() + " jobs");
		return jobList;
	}

	public Collection<JobStatus> getJobStatus(QueueStatus queue)
			throws SchedulerException {

		String qName = (queue != null) ? queue.getName() : null;
		BatchRequestSelectStatus request = new BatchRequestSelectStatus(qName);
		BatchReplyStatusSelect reply = (BatchReplyStatusSelect)serverCall(request);

		return reply.getAllStatus();

	}

	public void modifyJob(JobID jobID, String attr, String value)
		throws PBSException {

		BatchRequestModifyJob request = new BatchRequestModifyJob(
				jobID, attr, value);
		serverCall(request);

	}

	private void updateComment(JobID jobID) throws PBSException {

		modifyJob(jobID, "comment", "Job started on " + new Date());

	}

	public void runJob(JobID jobID, NodeStatus node) throws SchedulerException {

		updateComment(jobID);
		BatchRequestRunJob request = new BatchRequestRunJob(jobID, node.getName());
		serverCall(request);

	}

	public void runJob(JobStatus job, Collection<NodeInfo> nodes)
			throws SchedulerException {

		checkResourceAvailable((PBSJobStatus)job);
		updateComment(job.getJobID());

		BatchRequestRunJob request = new BatchRequestRunJob((PBSJobStatus)job, nodes);
		serverCall(request);

	}

	public void authenticateUser(String userName, int localPort) throws PBSException {

		BatchRequestAuthenticateUser request
			= new BatchRequestAuthenticateUser(userName, localPort);
		serverCall(request);

	}

	public void deleteJob(JobID jobID) throws SchedulerException {

		BatchRequestDeleteJob request = new BatchRequestDeleteJob(jobID);
		serverCall(request);

	}

	public void suspendJob(JobID jobID) throws SchedulerException {

		signalJob(jobID, SignalType.suspend);

	}

	public void resumeJob(JobID jobID) throws SchedulerException {

		signalJob(jobID, SignalType.resume);

	}

	public void holdJob(JobID jobID) throws SchedulerException {

		BatchRequestHoldJob request = new BatchRequestHoldJob(
				jobID, HoldJobType.SYSTEM);
		serverCall(request);

	}

	public void releaseJob(JobID jobID) throws SchedulerException {

		BatchRequestReleaseJob request = new BatchRequestReleaseJob(
				jobID, HoldJobType.SYSTEM);
		serverCall(request);

	}

	public void rerunJob(JobStatus job) throws SchedulerException {

		JobID jobID = job.getJobID();
		BatchRequestRerunJob request = new BatchRequestRerunJob(jobID);
		serverCall(request);

	}

	public void signalJob(JobID jobID, SignalType signal)
			throws SchedulerException {

		BatchRequestSignalJob request = new BatchRequestSignalJob(
				jobID, signal);
		serverCall(request);

	}

	public void checkResourceAvailable(PBSJobStatus job) throws SchedulerException {

		BatchRequestResourceQuery request = new BatchRequestResourceQuery(job);
		BatchReplyResourceQuery reply = (BatchReplyResourceQuery)serverCall(request);
		if (reply.isAvailable() == false) {
			throw new PBSException(PBSErrorCode.EXCQRESC);
		}

	}

}
